﻿//Description:MES定时任务处理类
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2023-8-9
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using BusinessRule.Common;
using System.Configuration;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace MESScheduledTask
{
    public partial class MESScheduledTask : ServiceBase
    {
        public MESScheduledTask()
        {
            InitializeComponent();
        }
        public List<string> m_taskList = new List<string>();//正在运算的任务
        public static readonly int intSync = Convert.ToInt32(ConfigurationManager.AppSettings["sync"].ToString());
        public static readonly int maxParallelSync = Convert.ToInt32(ConfigurationManager.AppSettings["maxParallelSync"].ToString());//最大并行任务数


        private System.Timers.Timer m_MonitorTimer;//服务监控定时器
        private System.Timers.Timer m_ApsSyncTimer;//排产计算定时器
        private System.Timers.Timer m_AutoStartSyncTimer;//自动开卡计算定时器
        /*热表相关定时任务的定时器*/
        private System.Timers.Timer m_RbApsShipSyncTimer;//转热表的排产转工计划接收定时器
        private System.Timers.Timer m_RbProductPrepareSyncTimer;//热表的生产准备定时器
        private System.Timers.Timer m_RbApsSyncTimer;//热表的滚动制造计划定时器
        private System.Timers.Timer m_TryApsSyncTimer;//预排任务定时器

        ApsScheduledTaskBusiness m_ApsSTB = new ApsScheduledTaskBusiness();
        AutoStartContainerTask m_AutoStartTask = new AutoStartContainerTask();
        /*热表相关定时任务对象*/
        RbApsShipReceiveTask m_RbApsShipRT = new RbApsShipReceiveTask();
        RbProductPrepareCheck m_RbProductPrepare = new RbProductPrepareCheck();
        RbApsScheduledTask m_RbAps = new RbApsScheduledTask();
        /*预排定时任务对象*/
        TryApsScheduledTask m_TryAps = new TryApsScheduledTask();

        protected override void OnStart(string[] args)
        {
            LogHelp.SetConfig();
            LogHelp.WriteLog("服务启动 处理器个数：" + Environment.ProcessorCount.ToString ());
            if (maxParallelSync > Environment.ProcessorCount) {
                LogHelp.WriteLog("计算机处理器数为：" + Environment.ProcessorCount.ToString() + " 请设置小于等于处理器数的并发数");
                return;
            }

            //排产定时任务线程
            SyncTimerStatr(ref m_ApsSyncTimer, m_ApsSyncTimer_Elapsed, intSync * 20);
            //自动开卡定时任务线程
            SyncTimerStatr(ref m_AutoStartSyncTimer, m_AutoStartSyncTimer_Elapsed, intSync * 20);
            //转热表的排产转工计划接收任务线程
            SyncTimerStatr(ref m_RbApsShipSyncTimer, m_RbApsShipSyncTimer_Elapsed, intSync * 20);
            //热表的生产准备任务线程
            SyncTimerStatr(ref m_RbProductPrepareSyncTimer, m_RbProductPrepareSyncTimer_Elapsed, intSync * 20);
            //热表的滚动制造计划任务线程
            SyncTimerStatr(ref m_RbApsSyncTimer, m_RbApsSyncTimer_Elapsed, intSync * 20);
            //预排定时任务线程
            SyncTimerStatr(ref m_TryApsSyncTimer, m_TryApsSyncTimer_Elapsed, intSync * 20);
            //服务监视定时器
            SyncTimerStatr(ref m_MonitorTimer, m_MonitorTimer_Elapsed, intSync * 60 * 10);//10分钟监视一次 
        }

        /// <summary>
        /// 传参启动新线程并运行方法
        /// </summary>
        /// <param name="timer"></param>
        /// <param name="m_timerElapsed"></param>
        private void SyncTimerStatr(ref System.Timers.Timer timer, Action<object, System.Timers.ElapsedEventArgs> m_timerElapsed, int intSync)
        {
            timer = new System.Timers.Timer();
            //timer.Enabled = false;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(m_timerElapsed);

            timer.Interval = intSync * 1000;
            //timer.Enabled = true;
            timer.Start();
        }

        /// <summary>
        /// 服务监视定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_MonitorTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            m_MonitorTimer.Enabled = false;
            LogHelp.WriteLog("--------------------------服务正常,正在执行的任务个数：" + m_taskList.Count.ToString() + "，正在执行的任务ID：" + JsonConvert.SerializeObject(m_taskList));             
            m_MonitorTimer.Enabled = true;
        }

        /// <summary>
        ///  APS启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_ApsSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //LogHelp.WriteLog("正在计算的定时任务:"+m_taskList.Count().ToString ());
                if (m_taskList.Count >= maxParallelSync)
                    return;
                m_ApsSyncTimer.Enabled = false;
                m_ApsSTB.RunDataSync(m_taskList);
                //m_ApsSTB.RunDataSyncTest(m_taskList);
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("m_ApsSyncTimer定时器异常", myError);
                LogHelp.WriteOrcaleError("MESScheduledTask_m_ApsSyncTimer" + "@^" + myError.Message + myError.StackTrace + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");//add:Wangjh 写入数据库   
            }
            finally
            { 
                m_ApsSyncTimer.Enabled = true;
            }
        }

        /// <summary>
        ///  自动开卡启动服务 add by zhangrj 20240109
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_AutoStartSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //LogHelp.WriteLog("正在计算的定时任务:"+m_taskList.Count().ToString ());
                if (m_taskList.Count >= maxParallelSync)
                    return;
                m_AutoStartSyncTimer.Enabled = false;
                m_AutoStartTask.RunTaskSync(m_taskList);
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("m_AutoStartSyncTimer定时器异常", myError);
                LogHelp.WriteOrcaleError("MESScheduledTask_m_AutoStartSyncTimer" + "@^" + myError.Message + myError.StackTrace + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");//add:Wangjh 写入数据库   
            }
            finally
            {
                m_AutoStartSyncTimer.Enabled = true;
            }
        }

        /// <summary>
        ///  热表转工排产计划接收启动服务 add by zhangrj 20240930
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_RbApsShipSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //LogHelp.WriteLog("正在计算的定时任务:"+m_taskList.Count().ToString ());
                if (m_taskList.Count >= maxParallelSync)
                    return;
                m_RbApsShipSyncTimer.Enabled = false;
                m_RbApsShipRT.RunTaskSync(m_taskList);
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("m_RbApsShipSyncTimer定时器异常", myError);
                LogHelp.WriteOrcaleError("MESScheduledTask_m_RbApsShipSyncTimer" + "@^" + myError.Message + myError.StackTrace + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");//add:Wangjh 写入数据库   
            }
            finally
            {
                m_RbApsShipSyncTimer.Enabled = true;
            }
        }

        /// <summary>
        ///  热表生产准备启动服务 add by zhangrj 20241009
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_RbProductPrepareSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //LogHelp.WriteLog("正在计算的定时任务:"+m_taskList.Count().ToString ());
                if (m_taskList.Count >= maxParallelSync)
                    return;
                m_RbProductPrepareSyncTimer.Enabled = false;
                m_RbProductPrepare.RunTaskSync(m_taskList);
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("m_RbProductPrepareSyncTimer定时器异常", myError);
                LogHelp.WriteOrcaleError("MESScheduledTask_m_RbProductPrepareSyncTimer" + "@^" + myError.Message + myError.StackTrace + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");//add:Wangjh 写入数据库   
            }
            finally
            {
                m_RbProductPrepareSyncTimer.Enabled = true;
            }
        }

        /// <summary>
        ///  热表滚动制造计划启动服务 add by zhangrj 20241009
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_RbApsSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //LogHelp.WriteLog("正在计算的定时任务:"+m_taskList.Count().ToString ());
                if (m_taskList.Count >= maxParallelSync)
                    return;
                m_RbApsSyncTimer.Enabled = false;
                m_RbAps.RunTaskSync(m_taskList);
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("m_RbApsSyncTimer定时器异常", myError);
                LogHelp.WriteOrcaleError("MESScheduledTask_m_RbApsSyncTimer" + "@^" + myError.Message + myError.StackTrace + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");//add:Wangjh 写入数据库   
            }
            finally
            {
                m_RbApsSyncTimer.Enabled = true;
            }
        }

        /// <summary>
        ///  预排启动服务 add by zhangrj 20250120
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_TryApsSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //LogHelp.WriteLog("正在计算的定时任务:"+m_taskList.Count().ToString ());
                if (m_taskList.Count >= maxParallelSync)
                    return;
                m_TryApsSyncTimer.Enabled = false;
                m_TryAps.RunTaskSync(m_taskList);
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("m_RbApsSyncTimer定时器异常", myError);
                LogHelp.WriteOrcaleError("MESScheduledTask_m_RbApsSyncTimer" + "@^" + myError.Message + myError.StackTrace + "@^" + "" + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + "");//add:Wangjh 写入数据库   
            }
            finally
            {
                m_TryApsSyncTimer.Enabled = true;
            }
        }

        protected override void OnStop()
        {
        }
    }
}
